package com.snowflakes.gruntr;

import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseQueryAdapter;
import com.parse.ParseRelation;
import com.parse.ParseUser;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class FriendRequests extends Activity {

	private ParseQueryAdapter<ParseObject> friendAdapter;
	private ListView listView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.friend_requests);

		friendAdapter = new FriendAdapter(this);

		listView = (ListView) findViewById(R.id.lvRequestList);
		listView.setAdapter(friendAdapter);
		friendAdapter.loadObjects();
		
		/*if(friendAdapter.isEmpty())
		{
			Toast.makeText(getBaseContext(), "No Pending Friend Requests", Toast.LENGTH_LONG)
			.show();
			finish();
		}*/

	}

	public void deny(View view) {

		ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
				"FriendRequests");

		String id = (String) view.getTag();

		query.whereEqualTo("objectId", id);

		ParseObject request = null;

		try {
			request = query.getFirst();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (request != null) {
				request.put("Denied", "true");
				request.saveInBackground();
			}
		}

		friendAdapter.loadObjects();
		if(friendAdapter.isEmpty())
		{
			finish();
		}
	}

	public void accept(View view) {

		ParseUser user = ParseUser.getCurrentUser();

		ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
				"FriendRequests");
		String id = (String) view.getTag();

		query.whereEqualTo("objectId", id);

		ParseObject request = null;

		try {
			request = query.getFirst();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (request != null) {
				request.put("Accepted", "true");
				ParseRelation<ParseUser> relation = user.getRelation("friends");
				relation.add(request.getParseUser("Sender"));
				user.saveInBackground();
				request.saveInBackground();
			}
			
		}

		friendAdapter.loadObjects();
		if(friendAdapter.isEmpty())
		{
			finish();
		}
	}

}
